

package com.beans;

import com.entidades.Passtable;
import java.util.Map;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;

/**
 * <p>A simple managed bean to mediate between the user
 * and the persistence layer.</p>
 * @author rlubke
 */
public class UserManager {
    
    /**
     * <p>The key for the session scoped attribute holding the
     * appropriate <code>Wuser</code> instance.</p>
     */
    public static final String USER_SESSION_KEY = "user";
    
    /**
     * <p>The <code>PersistenceContext</code>.</p>
     */
    @PersistenceContext 
    private EntityManager em;
    
    /**
     * <p>The transaction resource.</p>
     */
    @Resource 
    private UserTransaction utx;
    
    /**
     * <p>User properties.</p>
     */
    private String username;
    private String password;

    
    // -------------------------------------------------------------- Properties
    public String getUsername() {
        return username;
    }
    
    public void setUsername(String username) {
        this.username = username;
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
    
    // ---------------------------------------------------------- Public Methods
    
    
    /**
     * <p>Validates the user.  If the user doesn't exist or the password
     * is incorrect, the appropriate message is added to the current
     * <code>FacesContext</code>.  If the user successfully authenticates,
     * navigate them to the page referenced by the outcome <code>app-main</code>.
     * </p>
     *
     * @return <code>app-main</code> if the user authenticates, otherwise
     *  returns <code>null</code>
     */
    public String validateUser() {   
        FacesContext context = FacesContext.getCurrentInstance();
        Passtable user = getUser();
        System.out.println("Entra a validar usuario...");
        System.out.println("GetUser::: " + user.getUser().toString());
        System.out.println("username::: " + username);
        System.out.println("password::: " + password);
        if (user != null) {
            if (!user.getPass().equals(password)) {
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                           context.getApplication().evaluateExpressionGet(context, "Login incorrecto.", String.class)
                                           ,"Login error.");
                context.addMessage("logingrowl", message);
                return null;
            }

            context.getExternalContext().getSessionMap().put(USER_SESSION_KEY, user);
            
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
                    context.getApplication().evaluateExpressionGet(context, user.getUser() + ", Bienvenido!", String.class)
                    ,null);
            context.addMessage("logingrowl", message);
            
            setTipoUsuario(user.getIdPass());
            
            //pone la variable de sesion "SPAGINA" para que sea index
            Map sMap;
            sMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
            controlPrincipal bm = (controlPrincipal) sMap.get("cPri");
            bm.pagCentro = "index";
            
            return null;
            //return "app-main";
        } else {           
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                    context.getApplication().evaluateExpressionGet(context, "Login incorrecto.", String.class)
                    ,null);
            context.addMessage("logingrowl", message);
            return null;
        }
    }
    
    /**
     * <p>Creates a new <code>Wuser</code>.  If the specified user name exists
     * or an error occurs when persisting the Wuser instance, enqueue a message
     * detailing the problem to the <code>FacesContext</code>.  If the 
     * user is created, move the user back to the login view.</p>
     *
     * @return <code>login</code> if the user is created, otherwise
     *  returns <code>null</code>
     */
    /**
     * <p>When invoked, it will invalidate the user's session
     * and move them to the login view.</p>
     *
     * @return <code>login</code>
     */
    public String logout() {
        HttpSession session = (HttpSession)
             FacesContext.getCurrentInstance().getExternalContext().getSession(false);
        if (session != null) {
            session.invalidate();
        }
        //return "login";
        return "app-main";
        
    }
    
    // --------------------------------------------------------- Private Methods
    
    
    /**
     * <p>This will attempt to lookup a <code>Wuser</code> object
     * based on the provided user name.</p>
     *
     * @return a <code>Wuser</code> object associated with the current
     *  username, otherwise, if no <code>Wuser</code> can be found,
     *  returns <code>null</code>
     */
    public Passtable getUser() {
        try {
            Passtable user = (Passtable)
            em.createNamedQuery("Passtable.findByUser").
                    setParameter("user", username).getSingleResult();
            return user; 
        } catch (NoResultException nre) {
            return null;
        }
    }
    
    public void setTipoUsuario(Integer idUser) {
        Map sMap;
        sMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
        controlPrincipal bm = (controlPrincipal) sMap.get("cPri");
        try {
            Passtable use = (Passtable)
            em.createNamedQuery("Passtable.findByIdPass").
                    setParameter("idPass", idUser).getSingleResult();
            bm.esUsuario = true;
            
            if(use.getNivel().equals(1)){
                bm.esAdmin = true;
            }else{
                bm.esAdmin = false;
            }
            
        } catch (NoResultException nre) {
            bm.esUsuario = false;
            bm.esAdmin = false;
        }
        
    }
    
}
